package com.wehgu.admin.config.security.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wehgu.admin.common.Constant;
import com.wehgu.admin.config.security.dto.GlobalUser;
import com.wehgu.admin.config.security.dto.SecurityUser;
import com.wehgu.admin.entities.*;
import com.wehgu.admin.entities.vo.RoleVO;
import com.wehgu.admin.service.*;
import com.wehgu.admin.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p> 自定义userDetailsService - 登录认证详情 </p>
 */
@Service("UserDetailsService")
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private ISysRoleService sysRoleService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysUserDetailService sysUserDetailService;
    @Resource
    private ISysPermissionService sysPermissionService;
    @Resource
    private ISysRolePermService sysRolePermService;


    /***
     * 根据账号获取用户信息
     * @param username:
     * @return org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    //todo 登陆1
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // TODO 表中手机号为唯一值
        SysUserDetail accountInfo;
        SysUser userInfo;
        GlobalUser globalUser ;

        if (username.equals("admin")) {
            userInfo = sysUserService.getOne(new QueryWrapper<SysUser>()
                    .eq("user_uuid", 1).last("LIMIT 1"));
        } else {
            userInfo = sysUserService.getOne(new QueryWrapper<SysUser>()
                .eq("telephone", username).last("LIMIT 1"));

        }
        // 判断用户是否存在
        if (userInfo == null)
        {
            throw new UsernameNotFoundException("用户手机号不存在！");
        }
        // 用户存在获取账号信息
        accountInfo = sysUserDetailService.getOne(new QueryWrapper<SysUserDetail>()
                .eq("user_uuid", userInfo.getUserUuid()).last("LIMIT 1"));

        globalUser=setGlobalUser(userInfo,accountInfo);

        // 返回UserDetails实现类
        return new SecurityUser(globalUser);
    }

    /***
     * 根据token获取用户权限与基本信息
     *
     * @param token:
     * @return: SecurityUser
     */
    public SecurityUser getUserByToken(String token) {
        SysUserDetail accountInfo = null;
        SysUser userInfo = null;
        GlobalUser globalUser = new GlobalUser();
        SysRole sysRole=null;
        try {

            Claims claims = JwtUtil.parseToken(token);   // 获得claims
            log.info("解密Token");
            log.info(claims.toString());
            accountInfo = sysUserDetailService.getOne(new QueryWrapper<SysUserDetail>().eq("user_uuid", claims.get("userUID")));
            userInfo = sysUserService.getOne(new QueryWrapper<SysUser>().eq("user_uuid", claims.get("userUID")));

            //获取角色信息
            sysRole=sysRoleService.getOne(new QueryWrapper<SysRole>()
                    .eq("role_uuid",accountInfo.getRoleUuid()));
            globalUser=setGlobalUser(userInfo,accountInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<SysRole> roleList=new ArrayList<>();
        roleList.add(sysRole);

        globalUser.setType(Constant.PC);
        return new SecurityUser(globalUser, roleList,Constant.PC);
    }

    private GlobalUser setGlobalUser(SysUser userInfo, SysUserDetail accountInfo) {
        GlobalUser globalUser = new GlobalUser();

        //登录信息
        globalUser.setTelephone(userInfo.getTelephone());
        globalUser.setPassword(accountInfo.getPassword());
        //获取部门信息 还没写******先用uuids代替
        globalUser.setDeptName(accountInfo.getDeptUuid());

        globalUser.setUserUID(userInfo.getUserUuid());
        globalUser.setName(userInfo.getName());
        globalUser.setUnionId(accountInfo.getUnionId());//设置unionId
        //其他信息
        globalUser.setQq(accountInfo.getQq());
        globalUser.setEmail(userInfo.getEmail());
        //获取角色信息
        SysRole sysRole=sysRoleService.getOne(new QueryWrapper<SysRole>()
        .eq("role_uuid",accountInfo.getRoleUuid()));

        RoleVO roleVO=new RoleVO();
        roleVO.setRoleName(sysRole.getRoleUuid());
        roleVO.setRoleName(sysRole.getRoleName());
        roleVO.setDescription(sysRole.getDescription());
        globalUser.setRole(roleVO);

        //获取权限信息
        globalUser.setPermList(getRolePerms(sysRole.getRoleUuid()));

        return globalUser;
    }



    /***
     * 根据unionId获取用户权限与基本信息

     *
     * @param unionId:
     * @return: SecurityUser
     */
    public SecurityUser getUserByUnionId(String unionId) {

        SysUserDetail accountInfo = sysUserDetailService.getOne(new QueryWrapper<SysUserDetail>()
                .eq("union_id", unionId)
                .last("LIMIT 1"));
        SysUser userInfo = sysUserService.getOne(new QueryWrapper<SysUser>()
                .eq("user_uuid", accountInfo.getUserUuid())
                .last("LIMIT 1"));
        //获取角色信息
        SysRole sysRole=sysRoleService.getOne(new QueryWrapper<SysRole>()
                .eq("role_uuid",accountInfo.getRoleUuid()));

        GlobalUser globalUser=setGlobalUser(userInfo,accountInfo);

        globalUser.setType(Constant.WE_CHAT_MINI_PROGRAM);

        return new SecurityUser(globalUser, Collections.singletonList(sysRole),Constant.WE_CHAT_MINI_PROGRAM);
    }





    /**
     * 根据角色id获取角色权限信息
     *
     * @param roleUID
     * @return
     */
    public List<SysPermission> getRolePerms(String roleUID) {
        List<SysPermission> permList = new ArrayList<>();

        List<SysRolePerm> rolePermList=sysRolePermService.list(new QueryWrapper<SysRolePerm>()
        .eq("role_uuid",roleUID));

        for (SysRolePerm sysRolePerm:rolePermList) {
            SysPermission sysPermission=sysPermissionService.getOne(new QueryWrapper<SysPermission>()
            .eq("perm_uuid",sysRolePerm.getPermUuid()));

            permList.add(sysPermission);
        }


        return permList;
    }

}
